﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;

public partial class YCSearch : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["userName"] == null || Session["roleID"] == null)
        {
            Response.Redirect("Login.aspx");
            Response.End();
        }
        if (!Page.IsPostBack)
        {
            BindToDdlDep();
            BindToDdlYear();
            BindToDdlMonth();
            if (Request.QueryString["year"] != null)
            {
                ddlYear.SelectedValue = Request.QueryString["year"].ToString();
            }
            if (Request.QueryString["depid"] != null)
            {
                ddlDep.SelectedValue = Request.QueryString["depid"].ToString();
            }
            if (Request.QueryString["month"] != null)
            {
                ddlMonth.SelectedValue = Request.QueryString["month"].ToString();
            }
            if (Request.QueryString["status"] != null)
            {
                ddlStatus.SelectedValue = Request.QueryString["status"].ToString();
            }
            BindYCSearChResult(); 
        }
        if(Session["roleID"].ToString()!="1")
        {
            exportExcel.Enabled = false;
            btnCount.Enabled = false;
            
        }

    }
    //绑定异常信息
    protected void BindYCSearChResult()
    {
        RpYCList.DataSource = pds();
        RpYCList.DataBind();

    }
    private PagedDataSource pds()
    {
        int pageSize = 15;
        string dataYear = ddlYear.SelectedValue.ToString();
        string theMonth = ddlMonth.SelectedValue.ToString();
        string depID = ddlDep.SelectedValue.ToString();
        string status = ddlStatus.SelectedValue.ToString();
        string condition = " where 1=1 ";
        if (depID != "-1")
        {
            condition += "and DEPID=" + depID + " ";

        }
        if (theMonth != "-1")
        {
            condition += "and MONTH(ADDDATE)=" + theMonth + " ";
        }
        if (status != "-1")
        {
            condition += "and status='" + status + "'";
        }
        string YCMsgTabName = "YCMS" + dataYear;        
        string sqlString = "select * from " + YCMsgTabName + condition + " order by STATUS asc,ADDDATE DESC";
        DBOperation DBO = new DBOperation();
        DataSet ds = DBO.GetDataSet(sqlString, "temp");
        PagedDataSource pds = new PagedDataSource();
        pds.DataSource = ds.Tables["temp"].DefaultView;
        pds.AllowPaging = true;//允许分页
        pds.PageSize = pageSize;//单页显示项数
        int CurrentPage = 0;
        if (Request.QueryString["page"] != null)
        {
            CurrentPage = Convert.ToInt32(Request.QueryString["page"]);
        }
        pds.CurrentPageIndex = CurrentPage;
        return pds;
    }
    protected void ddlp_SelectedIndexChanged(object sender, EventArgs e)
    {//脚模板中的下拉列表框更改时激发
        string searchCondition ="&depid=" + ddlDep.SelectedValue + "&year=" + ddlYear.SelectedValue + "&month=" + ddlMonth.SelectedValue+"&status="+ddlStatus.SelectedValue;
        string pg = Convert.ToString((Convert.ToInt32(((DropDownList)sender).SelectedValue) - 1));//获取列表框当前选中项
        Response.Redirect("YCSearch.aspx?page=" + pg+searchCondition);//页面转向
    }

    protected void RpYCList_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        string searchCondition = "&depid=" + ddlDep.SelectedValue + "&year=" + ddlYear.SelectedValue + "&month=" + ddlMonth.SelectedValue + "&status=" + ddlStatus.SelectedValue;
        if (e.Item.ItemType == ListItemType.Footer)
        {
            DropDownList ddlp = (DropDownList)e.Item.FindControl("ddlp");

            HyperLink lpfirst = (HyperLink)e.Item.FindControl("hlfir");
            HyperLink lpprev = (HyperLink)e.Item.FindControl("hlp");
            HyperLink lpnext = (HyperLink)e.Item.FindControl("hln");
            HyperLink lplast = (HyperLink)e.Item.FindControl("hlla");

            pds().CurrentPageIndex = ddlp.SelectedIndex;

            int n = Convert.ToInt32(pds().PageCount);//n为分页数
            int i = Convert.ToInt32(pds().CurrentPageIndex);//i为当前页

            Label lblpc = (Label)e.Item.FindControl("lblpc");
            lblpc.Text = n.ToString();
            Label lblp = (Label)e.Item.FindControl("lblp");
            lblp.Text = Convert.ToString(pds().CurrentPageIndex + 1);

            if (!IsPostBack)
            {
                for (int j = 0; j < n; j++)
                {
                    ddlp.Items.Add(Convert.ToString(j + 1));
                }
            }

            if (i <= 0)
            {
                lpfirst.Enabled = false;
                lpprev.Enabled = false;
                lplast.Enabled = true;
                lpnext.Enabled = true;
            }
            else
            {
                lpprev.NavigateUrl = "?page=" + (i - 1) + searchCondition;
            }
            if (i >= n - 1)
            {
                lpfirst.Enabled = true;
                lplast.Enabled = false;
                lpnext.Enabled = false;
                lpprev.Enabled = true;
            }
            else
            {
                lpnext.NavigateUrl = "?page=" + (i + 1) + searchCondition;
            }

            lpfirst.NavigateUrl = "?page=0" + searchCondition;//向本页传递参数page
            lplast.NavigateUrl = "?page=" + (n - 1) + searchCondition;

            ddlp.SelectedIndex = Convert.ToInt32(pds().CurrentPageIndex);//更新下拉列表框中的当前选中页序号
        }
        //根据权限处理删除按钮
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Button btnDel = (Button)e.Item.FindControl("btnDel");
            btnDel.Attributes.Add("onclick", "return confirm('你确定要删除该异常记录吗？');");
            if (Session["roleID"].ToString() != "1")
            {
                btnDel.Text = "无权限";
                btnDel.Enabled = false;
            }
        }
    }

    //绑定数据到选择年份下拉列表
    private void BindToDdlYear()
    {
        BasicClass BC = new BasicClass();
        int currentYear = Convert.ToInt32(DateTime.Now.Year.ToString());
        Hashtable htYear = BC.CreateHashtable(currentYear, currentYear);
        ddlYear.DataSource = htYear;
        ddlYear.DataTextField = "value";
        ddlYear.DataValueField = "key";
        ddlYear.DataBind();
    }
    //绑定数据到DdlDep控件
    protected void BindToDdlDep()
    {
        DBOperation DBO = new DBOperation();
        string sqlString = "select DEPID,DEPNAME from DEPARTMENT where STATUS=1 order by DEPID ASC";
        SqlDataReader sdr = DBO.GetDataReader(sqlString);
        ddlDep.DataSource = sdr;
        ddlDep.DataTextField = "DEPNAME";
        ddlDep.DataValueField = "DEPID";
        ddlDep.DataBind();
        ddlDep.Items.Insert(0, new ListItem("全部", "-1"));
        sdr.Close();

    }
    //绑定数据到月份下拉列表，默认选择当前月
    private void BindToDdlMonth()
    {
        int currentMonth = Convert.ToInt32(DateTime.Now.Month.ToString());
        BasicClass BC = new BasicClass();
        Hashtable htMonth = BC.CreateHashtable(1, 12);
        ddlMonth.DataSource = htMonth;
        ddlMonth.DataTextField = "value";
        ddlMonth.DataValueField = "key";
        ddlMonth.DataBind();
        ddlMonth.Items.Insert(0, new ListItem("全部", "-1"));
    }
    //查询
    protected void btnSearchYC_Click(object sender, EventArgs e)
    {        
        string year = ddlYear.SelectedValue.ToString();
        string month = ddlMonth.SelectedValue.ToString();
        string depid = ddlDep.SelectedValue.ToString();
        string status = ddlStatus.SelectedValue.ToString();
        string toURL = "YCSearch.aspx?year=" + year + "&month=" + month + "&depid=" + depid + "&status=" + status+"";
        Response.Redirect(toURL);
    }
    protected void exportExcel_Click(object sender, EventArgs e)
    {
        string dataYear = ddlYear.SelectedValue.ToString();
        string theMonth = ddlMonth.SelectedValue.ToString();
        string depID = ddlDep.SelectedValue.ToString();
        string status = ddlStatus.SelectedValue.ToString();
        string condition = " where 1=1 ";
        if (depID != "-1")
        {
            condition += "and DEPID=" + depID + " ";

        }
        if (theMonth != "-1")
        {
            condition += "and MONTH(ADDDATE)=" + theMonth + "";
        }
        if (status != "-1")
        {
            condition += "and status='" + status + "'";
        }
        string YCMsgTabName = "YCMS" + dataYear;        
        string sqlString = "select * from " + YCMsgTabName + condition + " order by STATUS asc,ADDDATE DESC";
        DBOperation DBO = new DBOperation();
        DataSet ds = DBO.GetDataSet(sqlString, "temp");

        
        dg.DataSource = ds;
        dg.DataBind();

        string Month = DateTime.Now.Month.ToString();
        string FileName = Month + "月份异常";
        System.IO.StringWriter sw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
        dg.RenderControl(hw);

        Response.Clear();
        Response.ContentType = "application/vnd.ms-excel";
        Response.Charset = "";
        Page.EnableViewState = false;

        Response.AddHeader("content-disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls");
        Response.Write("<html><head><meta http-equiv=Content-Type content=\"text/html\"></head><body><center>");
        Response.Write(sw.ToString());
        Response.Write("</center></body></html>");
        Response.End();
    }
    //将用户名换成真名，将部门ID换成部门名称
    protected void dg_ItemDataBound(object sender, DataGridItemEventArgs e)
    {
        
        switch (e.Item.ItemType)
        {
            case ListItemType.AlternatingItem:
            case ListItemType.Item:
                {
                    string name = e.Item.Cells[9].Text;
                    string  depID =e.Item.Cells[10].Text;
                    string nameP = e.Item.Cells[11].Text;
                    string tureName = BasicClass.GetTrueNameByUserName(name);
                    string depName = BasicClass.GetDepNameByDepID(depID);
                    string trueNameP = BasicClass.GetTrueNameByUserName(nameP);
                    Label lblTrueName = (Label)e.Item.Cells[9].FindControl("trueName");
                    Label lblDepName = (Label)e.Item.Cells[10].FindControl("depName");
                    Label lblTrueNameP = (Label)e.Item.Cells[11].FindControl("trueNamep");
                    Label lblResult=(Label)e.Item.Cells[8].FindControl("lblResult");
                    lblTrueName.Text = tureName;
                    lblTrueNameP.Text = trueNameP;
                    lblDepName.Text = depName;
                    string status=e.Item.Cells[12].Text;

                    switch (status)
                    {
                        case "0":
                            lblResult.Text="审核中...";
                            break;
                        case "1":
                            lblResult.Text="审核完成";
                            break;

                    }

                }
                break;

        }

    }
    //该重写方法不可以删除！！！！！！！
    public override void VerifyRenderingInServerForm(Control control)
    {
    }

    protected void RpYCList_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        string YCID = e.CommandArgument.ToString();
        if (e.CommandName == "del")
        {
            string theYear = YCID.Substring(2, 4);
            string sqlString = "select * from YCFILES" + theYear + " where YCID='" + YCID + "'";
            DBOperation DBO = new DBOperation();
            SqlDataReader sdr = DBO.GetDataReader(sqlString);
            string prefixPath = Server.MapPath("files").ToString();
            string tempFilePath = prefixPath;
            while (sdr.Read())
            {
                tempFilePath = prefixPath;
                tempFilePath += sdr["FILENAME"].ToString();
                if (File.Exists(tempFilePath))
                {
                    File.Delete(tempFilePath);
                }

            }
            sdr.Close();
            YCDeal YCd = new YCDeal();
            if (YCd.DelYC(YCID))
            {
                Response.Redirect("YCList.aspx");
            }
            else
            {
                Response.Write("<script language='javascript'>alert('Sorry!异常删除失败！');</script>");

            }
        }
    }
    protected void btnCount_Click(object sender, EventArgs e)
    {
        Response.Redirect("Analyse.aspx");
    }
}
